const router = require('koa-router')();
const path = require('path');
const fs = require('fs');
const svgCaptcha = require('svg-captcha');
const jwt = require("jsonwebtoken");
const mysql = require('mysql');


router.get('/captcha', async (ctx) => {
  const captcha = svgCaptcha.create(
  { 
    size: 4, //字母个数
    noise: 2, //干扰线个数
    width: 280, //宽度
    height: 60, //高度
    color: true //文字颜色
  });

  ctx.response.type = "svg"
  ctx.session.captcha = captcha.text;
  
  ctx.body = { 
    code:200,
    data:{svg: captcha.data},
    msg:'success'
  }
});


router.post('/login', async (ctx) => {
  let result = await ctx.db.Excute("select * from users");

  const { username, password, captcha } = ctx.request.body;
  if (captcha !== ctx.session.captcha) {
    ctx.body = { success: false, message: "验证码错误！" };
    return;
  }
  const user = result.find((u) => u.username === username && u.password === password);
  if(user) {
    let token = jwt.sign(
      {username: username},
      "test",
      {expiresIn: 1000}
    )
    ctx.body = { success: true, message: "登录成功！", token: token };
  }  
  else ctx.body = { success: false, message: "用户名或密码错误" };
})

module.exports = router;